package sort.merge;

/**
 * @author justnow
 * Created on 2020-09-24
 * Description
 *
 * 手撕归并，bug free的内容总结
 *
 */
public class MergetSort2 {

    public int[] sort(int[] a, int low, int high) {
        if (low < high) {
            int mid = (low + high) / 2;
            sort(a, low, mid);
            sort(a, mid + 1, high);
            merge(a, low, high);
        }
        return a;
    }

    private void merge(int[] a, int low, int high) {
        int[] temp = new int[high - low + 1];
        int mid = (low + high) / 2;
        int index1 = low, index2 = mid + 1, k = 0;
        while (index1 <= mid && index2 <= high) {
            if (a[index1] < a[index2]) {
                temp[k++] = a[index1++];
            } else {
                temp[k++] = a[index2++];
            }
        }

        while (index1 <= mid) {
            temp[k++] = a[index1++];
        }

        while (index2 <= high) {
            temp[k++] = a[index2++];
        }

        for (int i = 0; i < temp.length; i++) {
            a[low + i] = temp[i];
        }
    }

    public static void main(String[] args) {
        MergetSort2 mergetSort2 = new MergetSort2();
        int[] a = {10, 7, 17, 20, 5, 4, 20, 3};
        mergetSort2.sort(a, 0, a.length - 1);
        for (int i : a) {
            System.out.print(i + " ");
        }
    }
}
